/*
 * D-Bus Java Implementation Copyright (c) 2005-2006 Matthew Johnson This
 * program is free software; you can redistribute it and/or modify it under the
 * terms of either the GNU Lesser General Public License Version 2 or the
 * Academic Free Licence Version 2.1. Full licence texts are included in the
 * COPYING file with this program.
 */
package org.freedesktop.dbus;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import cx.ath.matthew.unix.USOutputStream;

public class MessageWriter {
  private boolean      isunix;
  private OutputStream out;

  public MessageWriter(OutputStream out) {
    this.out = out;
    isunix = false;
    try {
      if (out instanceof USOutputStream) {
        isunix = true;
      }
    } catch (Throwable t) {
    }
    if (!isunix) {
      this.out = new BufferedOutputStream(this.out);
    }
  }

  public void close() throws IOException {
    out.close();
  }

  public void writeMessage(Message m) throws IOException {
    if (null == m) { return; }
    if (null == m.getWireData()) { return; }
    if (isunix) {
      ((USOutputStream) out).write(m.getWireData());
    } else {
      for (byte[] buf : m.getWireData()) {
        if (null == buf) {
          break;
        }
        out.write(buf);
      }
    }
    out.flush();
  }
}
